package vtt.android.dapanhc.activities.fragments;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import vtt.android.dapanhc.Constants;
import vtt.android.dapanhc.R;
import vtt.android.dapanhc.activities.SettingActivity;
import vtt.android.dapanhc.activities.TopActivity;
import vtt.android.dapanhc.utils.HttpRequestUtil;
import vtt.android.dapanhc.utils.HttpRequestUtil.IHttpResponseListener;
import vtt.android.dapanhc.utils.VttDateUtils;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.ads.AdView;

public class TopMenuFragment extends BaseFragment implements OnClickListener, IHttpResponseListener {

	public interface Listener {
        public void onStartChallenge();
        public void onPracticeRequested();
        public void onShowAchievementsRequested();
        public void onShowLeaderboardsRequested();
        public void onSignInButtonClicked();
        public void onSignOutButtonClicked();
    }
	
	private TopActivity topActivity;
	private Listener mListener = null;
    private Timer timer;
	private TextView tvTimer;
	private Button btnChallenge;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		View v = inflater.inflate(R.layout.fragment_top_menu, container, false);
		btnChallenge = (Button) v.findViewById(R.id.btn_challenge);
		btnChallenge.setOnClickListener(this);
		
		tvTimer = (TextView) v.findViewById(R.id.tvTimer);
		
		v.findViewById(R.id.btn_practice).setOnClickListener(this);
		v.findViewById(R.id.btn_leaderboard).setOnClickListener(this);
		v.findViewById(R.id.btn_achievement).setOnClickListener(this);
		v.findViewById(R.id.btn_setting).setOnClickListener(this);
		v.findViewById(R.id.btn_apprate).setOnClickListener(this);
		v.findViewById(R.id.sign_in_button).setOnClickListener(this);
		v.findViewById(R.id.sign_out_button).setOnClickListener(this);
		
		// Look up the AdView as a resource and load a request.
		AdView adView = (AdView) v.findViewById(R.id.adView);
	    loadAdmob(adView);
	    
        return v;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		topActivity = (TopActivity) activity;
		VttGA.sendView(topActivity, "/top_screen");
		
		// get date from server
		final HttpRequestUtil httpRequestUtil = new HttpRequestUtil(this);
		httpRequestUtil.makeRequestGET(Constants.API_GET_TIMEZONE, "");
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//btnChallenge.setTextColor(topActivity.getResources().getColor(R.color.gray));
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(timer != null){
			timer.cancel();
		}
	}

	public void setListener(Listener l) {
        mListener = l;
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_challenge:
			mListener.onStartChallenge();
			break;
		case R.id.btn_practice:
			mListener.onPracticeRequested();
			break;
		case R.id.btn_leaderboard:
			mListener.onShowLeaderboardsRequested();
			break;
		case R.id.btn_achievement:
			mListener.onShowAchievementsRequested();
			break;
		case R.id.btn_setting:
			Intent intentSetting = new Intent(getActivity(), SettingActivity.class);
			startActivity(intentSetting);
			break;
		case R.id.btn_apprate:
			VttUtils.openGooglePlayMarket(getActivity(), getActivity().getPackageName());
			break;
		case R.id.sign_in_button:
			// start the asynchronous sign in flow
			mListener.onSignInButtonClicked();
			break;
		case R.id.sign_out_button:
			// sign out.
			mListener.onSignOutButtonClicked();
			break;
		}
	}
	
	@Override
	public void onSuccess(Object result) {
		log.d("VTT>>> result " + result);
		if(result != null){
			
			tvTimer.setVisibility(View.VISIBLE);
			try {
				JSONObject jsonObject = new JSONObject((String)result);
				JSONObject timeZone = (JSONObject) jsonObject.getJSONObject("data").getJSONArray("time_zone").get(0);
				String localtime = timeZone.getString("localtime");
				log.d("VTT>>> localtime " + localtime);
				// display timer clock
				startTimerClock(localtime);
				
				localtime = localtime.split(" ")[0].replace("-", "");
				log.d("VTT>>> localtime " + localtime);
				
				String curDay = VttDateUtils.getCurrentDayString(topActivity.sharedPreferences);
				log.d("VTT>>> curDay " + curDay);
				
				if(curDay.compareToIgnoreCase(localtime) < 0){
					log.d("VTT>>> is new day");
					// set new day
					topActivity.sharedPreferences.edit().putString(Constants.SHARE_KEY_CURRENT_DAY, localtime).commit();
					// reset practice
					topActivity.sharedPreferences.edit().putBoolean(Constants.SHARE_KEY_IS_PRACTICED, false).commit();
					
					btnChallenge.setTextColor(topActivity.getResources().getColor(android.R.color.black));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onFail() {
		log.e("VTT>>> onFail" + "");
		tvTimer.setVisibility(View.INVISIBLE);
	}
	
	private void startTimerClock(String day) {
		// clear timer
		if(timer != null){
			timer.cancel();
		}
		
		try {
			long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(day + ":00").getTime();
			final Calendar cal1 = Calendar.getInstance();
			cal1.setTimeInMillis(time);
			final SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
			TimerTask timerTask = new TimerTask() {
				@Override
				public void run() {
					topActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							tvTimer.setText(sf.format(cal1.getTime()));
						}
					});
					cal1.add(Calendar.SECOND, 1);
				}
			};
			
			timer = new Timer();
			timer.schedule(timerTask, 0,1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
